package com.ifuncat.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ifuncat.gulimall.common.constant.WareConstant;
import com.ifuncat.gulimall.common.utils.PageUtils;
import com.ifuncat.gulimall.common.utils.Query;
import com.ifuncat.gulimall.ware.dao.PurchaseDao;
import com.ifuncat.gulimall.ware.dao.PurchaseDetailDao;
import com.ifuncat.gulimall.ware.entity.PurchaseDetailEntity;
import com.ifuncat.gulimall.ware.entity.PurchaseEntity;
import com.ifuncat.gulimall.ware.entity.WareSkuEntity;
import com.ifuncat.gulimall.ware.service.PurchaseDetailService;
import com.ifuncat.gulimall.ware.service.PurchaseService;
import com.ifuncat.gulimall.ware.service.WareSkuService;
import com.ifuncat.gulimall.ware.vo.MergeVo;
import com.ifuncat.gulimall.ware.vo.PurchaseDoneVo;
import com.ifuncat.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private PurchaseDetailDao purchaseDetailDao;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();

        //如果没有选择任何采购单,则自动创建新单并合并
        if (null == purchaseId) {
            purchaseId = createNewPurchase();
        }

        //查询选中的采购单详情
        List<PurchaseDetailEntity> detailEntityList = getPurchaseDetailByIds(mergeVo.getItems(), purchaseId);

        //更新采购单详情状态
        purchaseDetailService.updateBatchById(detailEntityList);

        //更新采购单
        updatePurchase(purchaseId);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1);
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public void received(List<Long> ids) {
        //确保选中的采购单的状态为新建或已分配
        List<PurchaseEntity> list = getRightPurchase(ids);
        if (CollectionUtils.isEmpty(list)) return;

        //修改采购单状态
        this.updateBatchById(list);

        //改变采购单详情状态
        batchUpdatePurchaseDetailStatus(list);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void done(PurchaseDoneVo doneVo) {
        //1. 将状态为已完成的订购信息添加库存
        addStock(doneVo);
        //2. 更新订购详情
        updatePurchaseDetail(doneVo);
        //3. 更新采购单状态
        updatePurchaseStatus(doneVo);
    }

    /**
     * 更新采购单状态
     */
    private void updatePurchaseStatus(PurchaseDoneVo doneVo) {
        //是否存在采购失败的订购详情
        boolean flag = doneVo.getItems().stream().anyMatch(item -> WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode() == item.getStatus());
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(doneVo.getId());
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    /**
     * 更新订购详情
     */
    private void updatePurchaseDetail(PurchaseDoneVo doneVo) {
        List<PurchaseDetailEntity> list = doneVo.getItems().stream().map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(i.getItemId());
            if (i.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                purchaseDetailEntity.setStatus(i.getStatus());
            } else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
            }
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        //批量更新
        purchaseDetailService.updateBatchById(list);
    }

    /**
     * 采购已完成的添加到库存中
     */
    private void addStock(PurchaseDoneVo doneVo) {
        //采购已完成的id
        List<Long> detailIdList = doneVo.getItems().stream().filter(i -> WareConstant.PurchaseDetailStatusEnum.FINISH.getCode() == i.getStatus()).map(PurchaseItemDoneVo::getItemId).collect(Collectors.toList());
        //查询详情
        Collection<PurchaseDetailEntity> detailList = purchaseDetailService.listByIds(detailIdList);
        //添加库存
        if (CollectionUtils.isEmpty(detailList)) {
            return;
        }
        for (PurchaseDetailEntity entity : detailList) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            BeanUtils.copyProperties(entity, wareSkuEntity);
            wareSkuEntity.setStock(entity.getSkuNum());
            wareSkuService.addStock(wareSkuEntity);
        }
    }


    private void batchUpdatePurchaseDetailStatus(List<PurchaseEntity> list) {
        Set<Long> purchaseIdSet = list.stream().map(PurchaseEntity::getId).collect(Collectors.toSet());
        //根据purchaseId查询所有的detail
        List<PurchaseDetailEntity> detailEntityList = purchaseDetailDao.selectList(new QueryWrapper<PurchaseDetailEntity>().in("purchase_id", purchaseIdSet));
        //更新detail
        List<PurchaseDetailEntity> entityList = detailEntityList.stream().peek(item -> {
            item.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(entityList);
    }

    /**
     * 确保选中的采购单的状态为新建或已分配
     */
    private List<PurchaseEntity> getRightPurchase(List<Long> ids) {
        return ids.stream().map(this::getById).filter(Objects::nonNull)
                .filter(item -> WareConstant.PurchaseStatusEnum.CREATED.getCode() == item.getStatus() || WareConstant.PurchaseStatusEnum.ASSIGNED.getCode() == item.getStatus())
                .peek(item -> {
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode()); //设置为已领取
                    item.setUpdateTime(new Date());
                }).collect(Collectors.toList());
    }

    private void updatePurchase(Long purchaseId) {
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    private List<PurchaseDetailEntity> getPurchaseDetailByIds(List<Long> ids, Long purchaseId) {
        Collection<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByIds(ids);

        purchaseDetailEntities.forEach(item -> {
            if (WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() != item.getStatus() && WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode() != item.getStatus()) {
                throw new IllegalArgumentException("正在采购, 无法进行分配");
            }
        });

        return ids.stream().map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(purchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
    }

    private Long createNewPurchase() {
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
        purchaseEntity.setCreateTime(new Date());
        purchaseEntity.setUpdateTime(new Date());
        this.save(purchaseEntity);
        return purchaseEntity.getId(); //返回新创建采购单的id
    }

}